'use client';

import React, { useState, useEffect } from 'react';
import { Card, Table, Button, Input, Space, DatePicker, Select, Form, message, Row, Col, Typography } from 'antd';
import { SearchOutlined, ReloadOutlined } from '@ant-design/icons';
import { getAllAttendanceRecords, getAttendanceRecords } from '@/lib/attendance';
import Layout from '@/components/Layout';
import dayjs from 'dayjs';
import dynamic from 'next/dynamic';

const { Option } = Select;
const { Title } = Typography;

// 添加 dynamic 配置
export default dynamic(() => Promise.resolve(AttendanceManagement), {
  ssr: false,
  loading: () => null
});

interface AttendanceRecord {
  employeeId: string;
  checkInDate: string;
  isCheckIn: number;
  onWorkTime: string;
  offDutyTime: string;
  workingTime: string;
  overTime: string;
  checkInStatus: number;
  circumstance: number;
}

interface QueryParams {
  page: number;
  pageSize: number;
  employeeId?: string;
  checkInDate?: string;
  isCheckIn?: number;
  checkInStatus?: number;
  circumstance?: number;
}

interface ResponseData {
  code: number;
  msg: string;
  data: {
    row: AttendanceRecord[];
    total: number;
  };
}

const AttendanceManagement = () => {
  const [attendanceRecords, setAttendanceRecords] = useState<AttendanceRecord[]>([]);
  const [loading, setLoading] = useState(true);
  const [total, setTotal] = useState(0);
  const [form] = Form.useForm();
  const [queryType, setQueryType] = useState<'employee' | 'condition'>('condition');
  const [queryParams, setQueryParams] = useState<QueryParams>({
    page: 1,
    pageSize: 10
  });

  const checkInStatusText = (status: number): string => {
    const statusMap: Record<number, string> = {
      1: '上班中',
      2: '已下班',
      3: '未打卡',
      4: '迟到',
      5: '早退',
      6: '迟到加早退'
    };
    return statusMap[status] || '未知';
  };

  const circumstanceText = (circumstance: number): string => {
    const circumstanceMap: Record<number, string> = {
      1: '正常',
      2: '请假',
      3: '出差',
      4: '培训'
    };
    return circumstanceMap[circumstance] || '未知';
  };

  const loadAttendanceRecords = async () => {
    try {
      setLoading(true);
      console.log('【查询考勤记录】请求参数:', queryParams);

      if (queryType === 'employee' && queryParams.employeeId) {
        // 使用员工号查询
        console.log('【查询单个员工考勤】员工号:', queryParams.employeeId);
        const response = await getAttendanceRecords(queryParams.employeeId);
        console.log('【查询单个员工考勤】响应数据:', response.data);

        if (response.data.code === 1) {
          const records = response.data.data || [];
          setAttendanceRecords(records);
          setTotal(records.length);
          
          if (records.length === 0) {
            message.info('暂无考勤记录');
          }
        } else {
          console.error('获取考勤记录失败:', response.data.msg);
          setAttendanceRecords([]);
          setTotal(0);
          message.error(response.data.msg || '获取考勤记录失败');
        }
      } else if (queryType === 'condition') {
        // 使用条件查询
        const { employeeId, ...restParams } = queryParams; // 移除员工号参数
        const response = await getAllAttendanceRecords(restParams);
        console.log('【条件查询考勤】响应数据:', response.data);
        
        if (response.data.code === 1) {
          const records = response.data.data.row || [];
          const total = response.data.data.total || 0;
          
          setAttendanceRecords(records);
          setTotal(total);
          
          if (records.length === 0) {
            message.info('暂无考勤记录');
          }
        } else {
          console.error('获取考勤记录失败:', response.data.msg);
          setAttendanceRecords([]);
          setTotal(0);
          message.error(response.data.msg || '获取考勤记录失败');
        }
      }
    } catch (error) {
      console.error('请求失败:', error);
      setAttendanceRecords([]);
      setTotal(0);
      message.error('获取考勤记录失败');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    loadAttendanceRecords();
  }, [queryParams, queryType]);

  const handleSearch = (values: any) => {
    const { employeeId, checkInDate, isCheckIn, checkInStatus, circumstance } = values;
    const params: QueryParams = {
      page: 1,
      pageSize: queryParams.pageSize
    };

    if (queryType === 'employee') {
      if (!employeeId) {
        message.error('请输入员工号');
        return;
      }
      params.employeeId = employeeId;
    } else {
      if (checkInDate) params.checkInDate = dayjs(checkInDate).format('YYYY-MM-DD');
      if (isCheckIn !== undefined) params.isCheckIn = isCheckIn;
      if (checkInStatus !== undefined) params.checkInStatus = checkInStatus;
      if (circumstance !== undefined) params.circumstance = circumstance;
    }

    console.log('【搜索条件】提交参数:', params);
    setQueryParams(params);
  };

  const handleReset = () => {
    const params = {
      page: 1,
      pageSize: 10
    };
    console.log('【重置查询】重置参数:', params);
    form.resetFields();
    setQueryParams(params);
  };

  const handleQueryTypeChange = (value: 'employee' | 'condition') => {
    setQueryType(value);
    handleReset();
  };

  const handleTableChange = (pagination: any) => {
    const params = {
      ...queryParams,
      page: pagination.current,
      pageSize: pagination.pageSize
    };
    console.log('【分页查询】分页参数:', params);
    setQueryParams(params);
  };

  const columns = [
    {
      title: '员工号',
      dataIndex: 'employeeId',
      key: 'employeeId',
    },
    {
      title: '打卡日期',
      dataIndex: 'checkInDate',
      key: 'checkInDate',
    },
    {
      title: '是否签到',
      dataIndex: 'isCheckIn',
      key: 'isCheckIn',
      render: (isCheckIn: number) => isCheckIn === 1 ? '是' : '否',
    },
    {
      title: '上班打卡时间',
      dataIndex: 'onWorkTime',
      key: 'onWorkTime',
    },
    {
      title: '下班打卡时间',
      dataIndex: 'offDutyTime',
      key: 'offDutyTime',
    },
    {
      title: '上班工作时间',
      dataIndex: 'workingTime',
      key: 'workingTime',
    },
    {
      title: '加班时长',
      dataIndex: 'overTime',
      key: 'overTime',
    },
    {
      title: '打卡状态',
      dataIndex: 'checkInStatus',
      key: 'checkInStatus',
      render: (status: number) => checkInStatusText(status),
    },
    {
      title: '特殊情况',
      dataIndex: 'circumstance',
      key: 'circumstance',
      render: (circumstance: number) => circumstanceText(circumstance),
    },
  ];

  return (
    <Layout>
      <Card>
        <Title level={4}>考勤管理</Title>
        <Form
          form={form}
          onFinish={handleSearch}
          layout="vertical"
          style={{ marginBottom: 24 }}
        >
          <Row gutter={24}>
            <Col span={6}>
              <Form.Item label="查询方式">
                <Select value={queryType} onChange={handleQueryTypeChange}>
                  <Option value="employee">按员工号查询</Option>
                  <Option value="condition">按条件查询</Option>
                </Select>
              </Form.Item>
            </Col>
          </Row>

          {queryType === 'employee' ? (
            <Row gutter={24}>
              <Col span={6}>
                <Form.Item 
                  name="employeeId" 
                  label="员工工号"
                  rules={[{ required: true, message: '请输入员工号' }]}
                >
                  <Input placeholder="请输入员工工号" allowClear />
                </Form.Item>
              </Col>
              <Col span={18}>
                <Form.Item style={{ marginTop: 29 }}>
                  <Space>
                    <Button type="primary" htmlType="submit" icon={<SearchOutlined />}>
                      查询
                    </Button>
                    <Button icon={<ReloadOutlined />} onClick={handleReset}>
                      重置
                    </Button>
                  </Space>
                </Form.Item>
              </Col>
            </Row>
          ) : (
            <>
              <Row gutter={24}>
                <Col span={6}>
                  <Form.Item name="checkInDate" label="打卡日期">
                    <DatePicker style={{ width: '100%' }} />
                  </Form.Item>
                </Col>
                <Col span={6}>
                  <Form.Item name="isCheckIn" label="是否签到">
                    <Select allowClear placeholder="请选择签到状态">
                      <Option value={1}>是</Option>
                      <Option value={0}>否</Option>
                    </Select>
                  </Form.Item>
                </Col>
                <Col span={6}>
                  <Form.Item name="checkInStatus" label="打卡状态">
                    <Select allowClear placeholder="请选择打卡状态">
                      <Option value={1}>上班中</Option>
                      <Option value={2}>已下班</Option>
                      <Option value={3}>未打卡</Option>
                      <Option value={4}>迟到</Option>
                      <Option value={5}>早退</Option>
                      <Option value={6}>迟到加早退</Option>
                    </Select>
                  </Form.Item>
                </Col>
                <Col span={6}>
                  <Form.Item name="circumstance" label="特殊情况">
                    <Select allowClear placeholder="请选择特殊情况">
                      <Option value={1}>正常</Option>
                      <Option value={2}>请假</Option>
                      <Option value={3}>出差</Option>
                      <Option value={4}>培训</Option>
                    </Select>
                  </Form.Item>
                </Col>
              </Row>
              <Row>
                <Col span={24} style={{ textAlign: 'right' }}>
                  <Space>
                    <Button type="primary" htmlType="submit" icon={<SearchOutlined />}>
                      查询
                    </Button>
                    <Button icon={<ReloadOutlined />} onClick={handleReset}>
                      重置
                    </Button>
                  </Space>
                </Col>
              </Row>
            </>
          )}
        </Form>

        <Table
          columns={columns}
          dataSource={attendanceRecords}
          rowKey={(record) => `${record.employeeId}-${record.checkInDate}`}
          loading={loading}
          pagination={queryType === 'condition' ? {
            total,
            current: queryParams.page,
            pageSize: queryParams.pageSize,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total) => `共 ${total} 条记录`
          } : false}
          onChange={queryType === 'condition' ? handleTableChange : undefined}
        />
      </Card>
    </Layout>
  );
};